<%--
  Created by IntelliJ IDEA.
  User: 付志玲
  Date: 2025/6/3
  Time: 下午9:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--<html>--%>
<%--<head>--%>
<%--    <title>Title</title>--%>
<%--</head>--%>
<%--<body>--%>
<%--你好--%>
<%--</body>--%>
<%--</html>--%>
<%--<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>--%>

<%@ page import="java.sql.*" %>
<%@ page import="org.example.DBConnection" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生选课与成绩管理系统</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 自定义Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0A2463',
                        accent: '#3E92CC',
                        neutral: '#F5F7FA',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-hover {
                @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-1;
            }
            .btn-primary {
                @apply bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors;
            }
            .btn-secondary {
                @apply bg-gray-200 text-gray-800 px-4 py-2 rounded-lg hover:bg-gray-300 transition-colors;
            }
            .btn-danger {
                @apply bg-danger text-white px-4 py-2 rounded-lg hover:bg-danger/90 transition-colors;
            }
        }
    </style>

    <style>
        /* 动画效果 */
        .fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        /* 滚动条美化 */
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #a1a1a1;
        }

        /* 表格样式 */
        .table-responsive {
            overflow-x: auto;
        }

        /* 表单验证样式 */
        .error {
            color: #F53F3F;
            font-size: 0.875rem;
            margin-top: 0.25rem;
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-gray-800 min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-primary shadow-md fixed top-0 left-0 right-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-3">
            <div class="flex items-center space-x-2">
                <i class="fa fa-graduation-cap text-white text-2xl"></i>
                <h1 class="text-xl font-bold text-white">学生选课与成绩管理</h1>
            </div>
        </div>

        <div class="flex items-center space-x-4">
            <div class="flex items-center space-x-2 cursor-pointer group">
                <i class="fa fa-user-circle-o text-white text-xl"></i>
                <span class="hidden sm:block font-medium text-white">管理员</span>
            </div>
        </div>
    </div>
</header>

<div class="flex pt-16 min-h-screen">
    <!-- 主内容区域 -->
    <main class="flex-1 p-4 sm:p-6">
        <div class="fade-in">
            <!-- 页面标题 -->
            <div class="mb-6">
                <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">学生选课与成绩管理</h2>
                <p class="text-gray-500 mt-1">根据学号查询和管理学生选课与成绩信息</p>
            </div>

            <!-- 学号查询表单 -->
            <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
                <h3 class="text-lg font-medium text-gray-900 mb-4">查询学生选课信息</h3>
                <form id="search-form" class="flex flex-col sm:flex-row gap-4">
                    <div class="flex-1">
                        <label for="student-id" class="block text-sm font-medium text-gray-700 mb-1">学号</label>
                        <input type="text" id="student-id" name="student_id" required
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/30">
                        <p id="student-id-error" class="error hidden"></p>
                    </div>
                    <div class="flex items-end">
                        <button type="submit" id="search-btn" class="btn-primary">
                            <i class="fa fa-search mr-2"></i> 查询
                        </button>
                    </div>
                </form>
            </div>

            <!-- 学生信息展示 -->
            <div id="student-info" class="bg-white rounded-xl shadow-sm p-6 mb-6 hidden">
                <div class="flex flex-col sm:flex-row gap-6 items-start sm:items-center">
                    <div class="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                        <i class="fa fa-user text-2xl"></i>
                    </div>
                    <div>
                        <h3 id="student-name" class="text-xl font-bold text-gray-900"></h3>
                        <p class="text-gray-600 mt-1">
                            <span id="student-id-display" class="font-medium"></span> |
                            <span id="student-major"></span> |
                            <span id="student-grade"></span>级
                        </p>
                    </div>
                    <div class="ml-auto">
                        <button id="select-course-btn" class="btn-primary">
                            <i class="fa fa-plus mr-2"></i> 选课
                        </button>
                    </div>
                </div>
            </div>

            <!-- 课程列表 -->
            <div id="course-list" class="bg-white rounded-xl shadow-sm overflow-hidden mb-6 hidden">
                <div class="bg-gray-50 px-6 py-3 border-b border-gray-200">
                    <h3 class="font-medium text-gray-900">已选课程</h3>
                </div>
                <div class="table-responsive">
                    <table class="min-w-full">
                        <thead>
                        <tr class="bg-gray-50 border-b border-gray-200">
                            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程编号</th>
                            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程名称</th>
                            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学分</th>
                            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">授课教师</th>
                            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">成绩</th>
                            <th class="py-3 px-4 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200" id="courses-tbody">
                        <!-- 课程数据将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 成绩统计 -->
            <div id="score-stats" class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6 hidden">
                <div class="bg-white rounded-xl shadow-sm p-4 card-hover">
                    <div class="flex items-center">
                        <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-primary mr-4">
                            <i class="fa fa-book"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray-500">已选课程</p>
                            <p id="course-count" class="text-2xl font-bold text-gray-900">0</p>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm p-4 card-hover">
                    <div class="flex items-center">
                        <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center text-green-600 mr-4">
                            <i class="fa fa-check-circle"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray-500">已完成课程</p>
                            <p id="completed-count" class="text-2xl font-bold text-gray-900">0</p>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm p-4 card-hover">
                    <div class="flex items-center">
                        <div class="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 mr-4">
                            <i class="fa fa-line-chart"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray-500">平均成绩</p>
                            <p id="average-score" class="text-2xl font-bold text-gray-900">0</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- 选课模态框 -->
<div id="select-course-modal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
    <div class="absolute inset-0 bg-black bg-opacity-50 transition-opacity"></div>
    <div class="relative bg-white rounded-lg shadow-xl w-full max-w-3xl mx-4 overflow-hidden transform transition-all max-h-[90vh] flex flex-col">
        <div class="bg-primary text-white px-6 py-4 flex justify-between items-center">
            <h3 class="text-lg font-medium">选择课程</h3>
            <button id="close-select-modal" class="text-white hover:text-gray-200">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="p-6 overflow-y-auto flex-1">
            <div class="mb-4">
                <label for="course-search" class="block text-sm font-medium text-gray-700 mb-1">搜索课程</label>
                <div class="relative">
                    <input type="text" id="course-search" placeholder="搜索课程名称或编号..."
                           class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/30">
                    <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                </div>
            </div>

            <div id="available-courses" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                <!-- 可选课程将通过JavaScript动态填充 -->
            </div>
        </div>
        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
            <button id="cancel-select-btn" class="btn-secondary">取消</button>
            <button id="confirm-select-btn" class="btn-primary">确认选择</button>
        </div>
    </div>
</div>

<!-- 成绩编辑模态框 -->
<div id="edit-score-modal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
    <div class="absolute inset-0 bg-black bg-opacity-50 transition-opacity"></div>
    <div class="relative bg-white rounded-lg shadow-xl w-full max-w-md mx-4 overflow-hidden transform transition-all">
        <div class="bg-primary text-white px-6 py-4 flex justify-between items-center">
            <h3 id="edit-modal-title" class="text-lg font-medium">编辑成绩</h3>
            <button id="close-edit-modal" class="text-white hover:text-gray-200">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="p-6">
            <form id="edit-score-form">
                <input type="hidden" id="edit-course-code" name="course_code">
                <input type="hidden" id="edit-student-id" name="student_id">

                <div class="mb-4">
                    <label for="edit-course-name" class="block text-sm font-medium text-gray-700 mb-1">课程名称</label>
                    <input type="text" id="edit-course-name" disabled
                           class="w-full px-3 py-2 bg-gray-50 border border-gray-300 rounded-md">
                </div>

                <div class="mb-6">
                    <label for="edit-score" class="block text-sm font-medium text-gray-700 mb-1">成绩</label>
                    <input type="number" id="edit-score" name="score" min="0" max="100" step="0.5" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/30">
                    <p id="score-error" class="error hidden"></p>
                </div>

                <div class="flex justify-end space-x-3">
                    <button type="button" id="cancel-edit-btn" class="btn-secondary">取消</button>
                    <button type="submit" id="save-edit-btn" class="btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 操作结果提示 -->
<div id="toast" class="fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transform transition-all duration-300 opacity-0 translate-y-[-20px] max-w-sm">
    <div class="flex items-center">
        <i id="toast-icon" class="mr-3 text-xl"></i>
        <div>
            <p id="toast-message" class="text-sm font-medium"></p>
        </div>
    </div>
</div>

<!-- JavaScript -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取DOM元素
        const searchForm = document.getElementById('search-form');
        const studentIdInput = document.getElementById('student-id');
        const studentInfo = document.getElementById('student-info');
        const courseList = document.getElementById('course-list');
        const coursesTbody = document.getElementById('courses-tbody');
        const scoreStats = document.getElementById('score-stats');
        const courseCount = document.getElementById('course-count');
        const completedCount = document.getElementById('completed-count');
        const averageScore = document.getElementById('average-score');
        const studentName = document.getElementById('student-name');
        const studentIdDisplay = document.getElementById('student-id-display');
        const studentMajor = document.getElementById('student-major');
        const studentGrade = document.getElementById('student-grade');
        const selectCourseBtn = document.getElementById('select-course-btn');
        const selectCourseModal = document.getElementById('select-course-modal');
        const closeSelectModalBtn = document.getElementById('close-select-modal');
        const cancelSelectBtn = document.getElementById('cancel-select-btn');
        const confirmSelectBtn = document.getElementById('confirm-select-btn');
        const availableCourses = document.getElementById('available-courses');
        const courseSearch = document.getElementById('course-search');
        const editScoreModal = document.getElementById('edit-score-modal');
        const closeEditModalBtn = document.getElementById('close-edit-modal');
        const cancelEditBtn = document.getElementById('cancel-edit-btn');
        const editScoreForm = document.getElementById('edit-score-form');
        const toast = document.getElementById('toast');

        let currentStudentId = null;
        let selectedCourses = [];

        // 显示提示消息
        function showToast(message, type) {
            const toastIcon = document.getElementById('toast-icon');
            const toastMessage = document.getElementById('toast-message');

            // 设置提示类型样式
            if (type === 'success') {
                toast.classList.add('bg-green-50', 'border-l-4', 'border-green-500', 'text-green-700');
                toast.classList.remove('bg-red-50', 'border-l-4', 'border-red-500', 'text-red-700');
                toastIcon.classList.add('fa-check-circle', 'text-green-500');
                toastIcon.classList.remove('fa-exclamation-circle', 'text-red-500');
            } else {
                toast.classList.add('bg-red-50', 'border-l-4', 'border-red-500', 'text-red-700');
                toast.classList.remove('bg-green-50', 'border-l-4', 'border-green-500', 'text-green-700');
                toastIcon.classList.add('fa-exclamation-circle', 'text-red-500');
                toastIcon.classList.remove('fa-check-circle', 'text-green-500');
            }

            toastMessage.textContent = message;
            toast.classList.remove('opacity-0', 'translate-y-[-20px]');

            // 3秒后自动隐藏
            setTimeout(() => {
                toast.classList.add('opacity-0', 'translate-y-[-20px]');
            }, 3000);
        }

        // 验证学号
        function validateStudentId() {
            const studentId = studentIdInput.value.trim();
            const errorEl = document.getElementById('student-id-error');

            if (studentId === '') {
                errorEl.textContent = '请输入学号';
                errorEl.classList.remove('hidden');
                return false;
            }

            errorEl.classList.add('hidden');
            return true;
        }

        // 验证成绩
        function validateScore() {
            const score = document.getElementById('edit-score').value;
            const errorEl = document.getElementById('score-error');

            if (score === '' || isNaN(score) || score < 0 || score > 100) {
                errorEl.textContent = '请输入0-100之间的成绩';
                errorEl.classList.remove('hidden');
                return false;
            }

            errorEl.classList.add('hidden');
            return true;
        }

        // 查询学生信息
        function searchStudent() {
            if (!validateStudentId()) {
                return;
            }

            const studentId = studentIdInput.value.trim();
            currentStudentId = studentId;

            // 模拟加载状态
            const searchBtn = document.getElementById('search-btn');
            searchBtn.disabled = true;
            searchBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 查询中...';

            setTimeout(() => {
                // 模拟API请求获取学生信息
                const xhr = new XMLHttpRequest();
                xhr.open('GET', `get_student.jsp?id=${studentId}`, true);
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            const student = JSON.parse(xhr.responseText);
                            if (student) {
                                // 显示学生信息
                                studentName.textContent = student.name;
                                studentIdDisplay.textContent = student.student_id;
                                studentMajor.textContent = student.major;
                                studentGrade.textContent = student.grade;

                                // 显示学生信息和课程列表区域
                                studentInfo.classList.remove('hidden');
                                courseList.classList.remove('hidden');
                                scoreStats.classList.remove('hidden');

                                // 获取学生选课信息
                                fetchCourseSelection(studentId);
                            } else {
                                showToast('未找到该学生信息', 'error');
                                studentInfo.classList.add('hidden');
                                courseList.classList.add('hidden');
                                scoreStats.classList.add('hidden');
                            }
                        } else {
                            showToast('查询失败', 'error');
                        }

                        // 恢复按钮状态
                        searchBtn.disabled = false;
                        searchBtn.innerHTML = '<i class="fa fa-search mr-2"></i> 查询';
                    }
                };
                xhr.send();
            }, 800);
        }

        // 获取学生选课信息
        function fetchCourseSelection(studentId) {
            // 模拟API请求获取选课信息
            const xhr = new XMLHttpRequest();
            xhr.open('GET', `get_course_selection.jsp?student_id=${studentId}`, true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    const courses = JSON.parse(xhr.responseText);

                    // 清空表格
                    coursesTbody.innerHTML = '';

                    if (courses && courses.length > 0) {
                        // 填充课程数据
                        courses.forEach(course => {
                            const row = document.createElement('tr');
                            row.className = 'hover:bg-gray-50 transition-colors';

                            const scoreDisplay = course.score !== null ? course.score : '未录入';
                            const scoreClass = course.score !== null ? 'text-gray-900' : 'text-gray-500 italic';

                            row.innerHTML = `
                                    <td class="py-3 px-4 text-sm font-medium">${course.course_code}</td>
                                    <td class="py-3 px-4 text-sm">${course.course_name}</td>
                                    <td class="py-3 px-4 text-sm">${course.credit}</td>
                                    <td class="py-3 px-4 text-sm">${course.teacher}</td>
                                    <td class="py-3 px-4 text-sm ${scoreClass}">${scoreDisplay}</td>
                                    <td class="py-3 px-4 text-right">
                                        <button class="edit-score-btn text-primary hover:text-primary/80"
                                            data-code="${course.course_code}"
                                            data-name="${course.course_name}"
                                            data-score="${course.score || ''}">
                                            <i class="fa fa-pencil mr-1"></i> ${course.score != null ? '修改成绩' : '录入成绩'}
                                        </button>
                                    </td>
                                `;

                            coursesTbody.appendChild(row);
                        });

                        // 更新统计信息
                        updateScoreStats(courses);

                        // 添加编辑按钮事件监听
                        document.querySelectorAll('.edit-score-btn').forEach(btn => {
                            btn.addEventListener('click', function() {
                                const courseCode = this.dataset.code;
                                const courseName = this.dataset.name;
                                const score = this.dataset.score;

                                openEditScoreModal(courseCode, courseName, score);
                            });
                        });
                    } else {
                        // 无选课记录
                        coursesTbody.innerHTML = `
                                <tr>
                                    <td colspan="6" class="py-6 px-4 text-center text-gray-500">
                                        <div class="flex flex-col items-center">
                                            <i class="fa fa-info-circle text-2xl mb-2"></i>
                                            <p>该学生尚未选择任何课程</p>
                                        </div>
                                    </td>
                                </tr>
                            `;

                        // 重置统计信息
                        courseCount.textContent = '0';
                        completedCount.textContent = '0';
                        averageScore.textContent = '0';
                    }
                }
            };
            xhr.send();
        }

        // 更新成绩统计信息
        function updateScoreStats(courses) {
            const totalCourses = courses.length;
            let completedCourses = 0;
            let totalScore = 0;

            courses.forEach(course => {
                if (course.score !== null) {
                    completedCourses++;
                    totalScore += parseFloat(course.score);
                }
            });

            const avgScore = completedCourses > 0 ? (totalScore / completedCourses).toFixed(1) : '0';

            courseCount.textContent = totalCourses;
            completedCount.textContent = completedCourses;
            averageScore.textContent = avgScore;
        }

        // 打开选课模态框
        function openSelectCourseModal() {
            if (!currentStudentId) {
                showToast('请先查询学生信息', 'error');
                return;
            }

            // 清空已选课程
            selectedCourses = [];

            // 模拟加载状态
            availableCourses.innerHTML = `
                    <div class="col-span-full text-center py-10">
                        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                        <p class="mt-2 text-gray-500">加载课程中...</p>
                    </div>
                `;

            // 显示模态框
            selectCourseModal.classList.remove('hidden');
            document.body.classList.add('overflow-hidden');

            setTimeout(() => {
                // 模拟API请求获取可选课程
                const xhr = new XMLHttpRequest();
                xhr.open('GET', `get_available_courses.jsp?student_id=${currentStudentId}`, true);
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        const courses = JSON.parse(xhr.responseText);

                        // 清空课程列表
                        availableCourses.innerHTML = '';

                        if (courses && courses.length > 0) {
                            // 填充可选课程
                            courses.forEach(course => {
                                const courseCard = document.createElement('div');
                                courseCard.className = 'bg-white border border-gray-200 rounded-lg p-4 hover:border-primary transition-colors cursor-pointer';
                                courseCard.dataset.code = course.course_code;

                                courseCard.innerHTML = `
                                        <div class="flex items-start">
                                            <div class="flex-shrink-0">
                                                <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                                    <i class="fa fa-book"></i>
                                                </div>
                                            </div>
                                            <div class="ml-4">
                                                <h4 class="font-medium text-gray-900">${course.course_name}</h4>
                                                <p class="text-sm text-gray-500 mt-1">${course.course_code}</p>
                                                <div class="flex items-center mt-2">
                                                    <span class="text-xs px-2 py-1 bg-blue-100 text-blue-800 rounded-full">
                                                        ${course.credit}学分
                                                    </span>
                                                    <span class="ml-2 text-xs text-gray-500">${course.teacher}</span>
                                                </div>
                                            </div>
                                            <div class="ml-auto flex-shrink-0">
                                                <input type="checkbox" class="course-checkbox rounded text-primary focus:ring-primary"
                                                    data-code="${course.course_code}">
                                            </div>
                                        </div>
                                    `;

                                availableCourses.appendChild(courseCard);

                                // 添加点击事件
                                courseCard.addEventListener('click', function(e) {
                                    if (e.target.type !== 'checkbox') {
                                        const checkbox = this.querySelector('.course-checkbox');
                                        checkbox.checked = !checkbox.checked;
                                        updateSelectedCourses();
                                    }
                                });

                                // 添加复选框事件
                                const checkbox = courseCard.querySelector('.course-checkbox');
                                checkbox.addEventListener('change', updateSelectedCourses);
                            });
                        } else {
                            // 无可选课程
                            availableCourses.innerHTML = `
                                    <div class="col-span-full text-center py-10">
                                        <i class="fa fa-info-circle text-2xl text-gray-400 mb-2"></i>
                                        <p class="text-gray-500">没有可选的课程</p>
                                    </div>
                                `;
                            confirmSelectBtn.disabled = true;
                        }
                    }
                };
                xhr.send();
            }, 500);
        }

        // 更新已选课程列表
        function updateSelectedCourses() {
            selectedCourses = Array.from(document.querySelectorAll('.course-checkbox:checked'))
                .map(checkbox => checkbox.dataset.code);

            // 更新确认按钮状态
            confirmSelectBtn.disabled = selectedCourses.length === 0;
        }

        // 关闭选课模态框
        function closeSelectCourseModal() {
            selectCourseModal.classList.add('hidden');
            document.body.classList.remove('overflow-hidden');
        }

        // 确认选课
        function confirmCourseSelection() {
            if (selectedCourses.length === 0) {
                showToast('请选择至少一门课程', 'error');
                return;
            }

            // 模拟加载状态
            confirmSelectBtn.disabled = true;
            confirmSelectBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 提交中...';

            setTimeout(() => {
                // 模拟API请求提交选课
                const data = {
                    student_id: currentStudentId,
                    course_codes: selectedCourses
                };

                const xhr = new XMLHttpRequest();
                xhr.open('POST', 'select_course.jsp', true);
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            showToast('选课成功', 'success');
                            closeSelectCourseModal();
                            // 刷新选课信息
                            fetchCourseSelection(currentStudentId);
                        } else {
                            showToast('选课失败', 'error');
                        }

                        // 恢复按钮状态
                        confirmSelectBtn.disabled = false;
                        confirmSelectBtn.innerHTML = '确认选择';
                    }
                };
                xhr.send(JSON.stringify(data));
            }, 800);
        }

        // 打开编辑成绩模态框
        function openEditScoreModal(courseCode, courseName, score) {
            document.getElementById('edit-course-code').value = courseCode;
            document.getElementById('edit-student-id').value = currentStudentId;
            document.getElementById('edit-course-name').value = courseName;
            document.getElementById('edit-score').value = score || '';

            // 显示模态框
            editScoreModal.classList.remove('hidden');
            document.body.classList.add('overflow-hidden');
        }

        // 关闭编辑成绩模态框
        function closeEditScoreModal() {
            editScoreModal.classList.add('hidden');
            document.body.classList.remove('overflow-hidden');
            document.getElementById('score-error').classList.add('hidden');
        }

        // 保存编辑的成绩
        function saveEditedScore() {
            if (!validateScore()) {
                return;
            }

            const courseCode = document.getElementById('edit-course-code').value;
            const score = document.getElementById('edit-score').value;

            // 模拟加载状态
            const saveBtn = document.getElementById('save-edit-btn');
            saveBtn.disabled = true;
            saveBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';

            setTimeout(() => {
                // 模拟API请求保存成绩
                const data = {
                    student_id: currentStudentId,
                    course_code: courseCode,
                    score: parseFloat(score)
                };

                const xhr = new XMLHttpRequest();
                xhr.open('POST', 'update_score.jsp', true);
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            showToast('成绩更新成功', 'success');
                            closeEditScoreModal();
                            // 刷新选课信息
                            fetchCourseSelection(currentStudentId);
                        } else {
                            showToast('成绩更新失败', 'error');
                        }

                        // 恢复按钮状态
                        saveBtn.disabled = false;
                        saveBtn.innerHTML = '保存';
                    }
                };
                xhr.send(JSON.stringify(data));
            }, 800);
        }

        // 事件监听
        searchForm.addEventListener('submit', function(e) {
            e.preventDefault();
            searchStudent();
        });

        studentIdInput.addEventListener('input', function() {
            document.getElementById('student-id-error').classList.add('hidden');
        });

        selectCourseBtn.addEventListener('click', openSelectCourseModal);
        closeSelectModalBtn.addEventListener('click', closeSelectCourseModal);
        cancelSelectBtn.addEventListener('click', closeSelectCourseModal);
        confirmSelectBtn.addEventListener('click', confirmCourseSelection);

        courseSearch.addEventListener('input', function() {
            const keyword = this.value.toLowerCase().trim();
            const courseCards = document.querySelectorAll('#available-courses > div');

            courseCards.forEach(card => {
                const courseName = card.querySelector('h4').textContent.toLowerCase();
                const courseCode = card.querySelector('p').textContent.toLowerCase();

                if (courseName.includes(keyword) || courseCode.includes(keyword)) {
                    card.classList.remove('hidden');
                } else {
                    card.classList.add('hidden');
                }
            });
        });

        closeEditModalBtn.addEventListener('click', closeEditScoreModal);
        cancelEditBtn.addEventListener('click', closeEditScoreModal);

        editScoreForm.addEventListener('submit', function(e) {
            e.preventDefault();
            saveEditedScore();
        });

        document.getElementById('edit-score').addEventListener('input', function() {
            document.getElementById('score-error').classList.add('hidden');
        });
    });
</script>
</body>
</html>